﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Model.EntityModel;
using DataAccess;
using CustomControls;
using System.Collections.ObjectModel;

namespace Project
{
    /// <summary>
    /// Interaction logic for UpdateCitationContent.xaml
    /// </summary>
    public partial class UpdateCitationContent : UserControl
    {
        public long idComplaint;
        public long idCitation;
        String Hours;
        String Minutes;
        Actor ActorDenounced = new Actor();
        Person Denounced = new Person();
        Actor ActorAggressor = new Actor();
        Person Aggressor = new Person();
        Employee functionary = new Employee();
        Model.Functionary f = new Model.Functionary();
        SearchFunctionary search;
        Citation citation = new Citation();
        GrantDirectorPermissionWindows Director;
        SearchComplaintWindow sc;

        public UpdateCitationContent(long id, long idC)
        {
            InitializeComponent();
            UIWindowManager.SetWindowTitle(this, "Brigada De Protección a la Familia - Modificar Citación");
            SetRules();
            try
            {
                idComplaint = id;
                idCitation = idC;
                ActorDenounced = PersonAndActorDataAccess.GetActorByTypeAndComplaintId("Denunciante", idComplaint);
                Denounced = PersonAndActorDataAccess.GetPersonById(ActorDenounced.IdPerson);
                TxtBoxDenouncedName.Text = Denounced.Name;
                TxtBoxDenouncedPName.Text = Denounced.PaternalName;
                    TxtBoxDenouncedMName.Text = Denounced.MaternalName;
                ActorAggressor = PersonAndActorDataAccess.GetActorByTypeAndComplaintId("Agresor", idComplaint);
                Aggressor = PersonAndActorDataAccess.GetPersonById(ActorAggressor.IdPerson);
                TxtBoxAggressorName.Text = Aggressor.Name;
                TxtBoxAggressorPName.Text = Aggressor.PaternalName;
                    TxtBoxAggressorMName.Text = Aggressor.MaternalName;
                citation = CitationDataAccess.GetCitationByIdCitation(idCitation);
                f = DataBaseAccess.ReadEmployee(Convert.ToInt64(citation.IdEmployee));
                TxtBoxEmployeeName.Text = f.Name;
                TxtBoxEmployeePName.Text = f.PaternalName;
                TxtBoxemployeeMName.Text = f.MaternalName;
                TxtBoxEmployeRank.Text = f.Rank;
                datePickerCitationDate.SelectedDate=citation.CitationDate;
                String time=citation.CitationTime.ToString();
                string[] words = time.Split(':');
                String h = words[0];
                String m = words[1];
                cmbBoxHours.SelectedIndex=Convert.ToInt32(h);
                cmbBoxMinutes.SelectedIndex = Convert.ToInt32(m);              
            }
            catch
            {
                Xceed.Wpf.Toolkit.MessageBox.Show("Error en al extraer los datos", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void SetRules()
        {
             datePickerCitationDate.DisplayDateStart = DateTime.Now;
            datePickerCitationDate.DisplayDateEnd = DateTime.Now.AddMonths(10);
            TxtBoxAggressorName.AddValitationRule(new BlankValidRule());
            TxtBoxAggressorPName.AddValitationRule(new BlankValidRule());
            TxtBoxDenouncedName.AddValitationRule(new BlankValidRule());
            TxtBoxDenouncedPName.AddValitationRule(new BlankValidRule());
            TxtBoxAggressorName.IsEnabled = false;
            TxtBoxAggressorPName.IsEnabled = false;
            TxtBoxAggressorMName.IsEnabled = false;
            TxtBoxDenouncedName.IsEnabled = false;
            TxtBoxDenouncedPName.IsEnabled = false;
            TxtBoxDenouncedMName.IsEnabled = false;
            TxtBoxEmployeePName.AddValitationRule(new BlankValidRule());
            TxtBoxEmployeeName.AddValitationRule(new BlankValidRule());
            TxtBoxEmployeRank.AddValitationRule(new BlankValidRule());
        }

        private bool CheckHasErrors()
        {
            bool res = false;

            foreach (var ctrl in (Content as Grid).Children)
            {
                TextBox tb = ctrl as TextBox;
                if (tb != null)
                {
                    tb.GetBindingExpression(TextBox.TextProperty).UpdateSource();
                    if (Validation.GetHasError(tb))
                        res = true;
                }
                ValidationComboBox cb = ctrl as ValidationComboBox;
                if (cb != null)
                {
                    cb.LostFocusEventHandler(cb, null);
                    if (Validation.GetHasError(cb))
                        res = true;
                }
                ValidDatePicker dtp = ctrl as ValidDatePicker;
                if (dtp != null)
                {
                    dtp.GetBindingExpression(DatePicker.TextProperty).UpdateSource();
                    dtp.LostFocusEventHandler(dtp, null);
                    if (Validation.GetHasError(dtp))
                        res = true;
                }

            }
            return res;
        }

        private void cmbBoxHours_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cmbBoxHours.SelectedIndex != -1)
            {
                ComboBoxItem item = (ComboBoxItem)cmbBoxHours.SelectedValue;
                Hours = item.Content.ToString();
            }
        }

        private void cmbBoxMinutes_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cmbBoxMinutes.SelectedIndex != -1)
            {
                ComboBoxItem item = (ComboBoxItem)cmbBoxMinutes.SelectedValue;
                Minutes = item.Content.ToString();
            }
        }

        void getEmployeeEventHandler(object sender, RoutedEventArgs e)
        {
            try
            {
                functionary.CI = search.Employee.CI;
                f = DataBaseAccess.ReadEmployee(functionary.CI);
                functionary.Name = f.Name;
                functionary.PaternalName = f.PaternalName;
                functionary.MaternalName = f.MaternalName;
                functionary.Rank = f.Rank;
                search.Close();

                TxtBoxEmployeeName.Text = functionary.Name;
                TxtBoxEmployeePName.Text = functionary.PaternalName;
                TxtBoxemployeeMName.Text = functionary.MaternalName;
                TxtBoxEmployeRank.Text = functionary.Rank;
            }
            catch
            {
                Xceed.Wpf.Toolkit.MessageBox.Show("Ocurrio un error al obtener el empleado", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private void TxtBoxEmployeeRank_GotFocus(object sender, RoutedEventArgs e)
        {
            search = new SearchFunctionary();
            search.getEmployee += new RoutedEventHandler(getEmployeeEventHandler);
            search.ShowDialog();
            TxtBoxEmployeRank.Focusable = false;
        }

        private void TxtBoxEmployeeName_GotFocus(object sender, RoutedEventArgs e)
        {
            TxtBoxEmployeeRank_GotFocus(sender, e);
            TxtBoxEmployeeName.Focusable = false;
        }

        private void BtnSave_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!CheckHasErrors())
                {

                    citation.CitationDate = datePickerCitationDate.SelectedDate;
                    TimeSpan time = new TimeSpan(Convert.ToInt32(Hours), Convert.ToInt32(Minutes), 0);
                    citation.CitationTime = time;
                    //citation.IdComplaint = idComplaint;
                    if (functionary.CI == 0)
                    {
                        citation.IdEmployee = f.CI;
                    }
                    else
                    {
                        citation.IdEmployee = functionary.CI;
                    }
                    
                        citation = CitationDataAccess.UpdateCitation(citation.Id,citation);
                        if (citation != null)
                        {
                            MessageBoxResult result = MessageBox.Show("Citacion Modificada! Desea imprimirla?", "Informacion", MessageBoxButton.YesNo, MessageBoxImage.Question);
                            if (result == MessageBoxResult.Yes)
                            {
                                var items = new ObservableCollection<UserControl>();
                                items.Add(new PrintCitation(idComplaint, citation.Id));
                                var a = new PrintPreviewDialogV2(items);
                                a.ShowDialog();
                            }
                            else
                            {
                                Xceed.Wpf.Toolkit.MessageBox.Show("Puede imprimir la citacion posteriormente, entrando a Ver Denuncias, click sobre la denuncia selecciona la opción Ver Citaciones seleccionando por fecha la citacion que desea",
                                                                "Información!", MessageBoxButton.OK, MessageBoxImage.Information);
                            }
                            UIWindowManager.CleanWindow(this);
                        }
                        else
                        {
                            Xceed.Wpf.Toolkit.MessageBox.Show("Error al modificar la citacion", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    
                }
            }
            catch
            {
                Xceed.Wpf.Toolkit.MessageBox.Show("La operacion no puede completarse", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        

        private void TxtBoxEmployeePName_GotFocus(object sender, RoutedEventArgs e)
        {
            TxtBoxEmployeeRank_GotFocus(sender, e);
            TxtBoxEmployeePName.Focusable = false;
        }

        private void TxtBoxemployeeMName_GotFocus(object sender, RoutedEventArgs e)
        {
            TxtBoxEmployeeRank_GotFocus(sender, e);
            TxtBoxemployeeMName.Focusable = false;
        }

        public void Charge()
        {
            try
            {
                ActorDenounced = PersonAndActorDataAccess.GetActorByTypeAndComplaintId("Denunciante", idComplaint);
                Denounced = PersonAndActorDataAccess.GetPersonById(ActorDenounced.IdPerson);
                ActorAggressor = PersonAndActorDataAccess.GetActorByTypeAndComplaintId("Agresor", idComplaint);
                Aggressor = PersonAndActorDataAccess.GetPersonById(ActorAggressor.IdPerson);
                TxtBoxDenouncedName.Text = Denounced.Name.ToString();
                TxtBoxDenouncedPName.Text = Denounced.PaternalName;
                TxtBoxDenouncedMName.Text = Denounced.MaternalName;
                TxtBoxAggressorName.Text = Aggressor.Name;
                TxtBoxAggressorPName.Text = Aggressor.PaternalName;
                TxtBoxAggressorMName.Text = Aggressor.MaternalName;
                citation.IdComplaint = idComplaint;
            }
            catch
            {
                Xceed.Wpf.Toolkit.MessageBox.Show("Error en al obtener datos de nuestra base de datos", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }


        }

        private void btnKeyComplainant_Click(object sender, RoutedEventArgs e)
        {
            Director = new GrantDirectorPermissionWindows();
            bool result = Convert.ToBoolean(Director.ShowDialog());
            if (result)
            {
                sc = new SearchComplaintWindow();
                (sc.Content.Children[0] as SearchComplaint).listViewComplaints.MouseDoubleClick += (getComplaintEventHandler);
                sc.ShowDialog();
            }
            else
                MessageBox.Show("Datos incorrectos", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
        }

        void getComplaintEventHandler(object sender, RoutedEventArgs e)
        {
            try
            {
                idComplaint = (sc.Content.Children[0] as SearchComplaint).SelectedComplaintId;
                Charge();
            }
            catch
            {
                Xceed.Wpf.Toolkit.MessageBox.Show("Ocurrio un error al asignar denuncia", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private void btnKeyDenounced_Click(object sender, RoutedEventArgs e)
        {
            btnKeyComplainant_Click(sender, e);
        }
    }
}
